package com.zhentao.controller;

import com.zhentao.annotation.OperationLog;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@RestController
@RequestMapping("/dataCollectionWarehousing")
@CrossOrigin
public class dataCollectionWarehousingController {

    @Autowired
    private DataCollectionService dataCollectionService;
    
    @Autowired
    private DataStorageService dataStorageService;
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private CustomsDataLogService customsDataLogService;
    
    @Autowired
    private CustomsAreaConfigService customsAreaConfigService;

    /**
     * 手工录入数据
     */
    @OperationLog(bizModule = 1, bizType = 1, description = "手工录入海关数据")
    @PostMapping("/manualInput")
    public Map<String, Object> manualInput(@RequestBody DataCollection dataCollection) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置数据类型为手工录入
            dataCollection.setDataType(3);
            dataCollection.setStatus(1); // 待入库
            dataCollection.setCreateTime(new Date());
            
            // 保存采集数据
            boolean success = dataCollectionService.save(dataCollection);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "数据录入成功");
                result.put("data", dataCollection);
            } else {
                result.put("code", 500);
                result.put("message", "数据录入失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * CSV文件上报
     */
    @OperationLog(bizModule = 1, bizType = 1, description = "CSV文件上报数据")
    @PostMapping("/csvUpload")
    public Map<String, Object> csvUpload(@RequestParam("file") MultipartFile file,
                                       @RequestParam("customsArea") String customsArea,
                                       @RequestParam("userId") Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (file.isEmpty()) {
                result.put("code", 400);
                result.put("message", "文件不能为空");
                return result;
            }
            
            // 解析CSV文件并批量保存数据
            List<DataCollection> dataList = parseCsvFile(file, customsArea, userId);
            
            if (!dataList.isEmpty()) {
                boolean success = dataCollectionService.saveBatch(dataList);
                
                if (success) {
                    result.put("code", 200);
                    result.put("message", "CSV文件上报成功");
                    result.put("data", "成功导入" + dataList.size() + "条数据");
                } else {
                    result.put("code", 500);
                    result.put("message", "数据保存失败");
                }
            } else {
                result.put("code", 400);
                result.put("message", "文件解析失败或无有效数据");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 数据入库操作
     */
    @OperationLog(bizModule = 1, bizType = 2, description = "数据入库操作")
    @PostMapping("/warehousing")
    public Map<String, Object> warehousing(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer collectionId = (Integer) params.get("collectionId");
            Integer userId = (Integer) params.get("userId");
            
            // 获取采集数据
            DataCollection dataCollection = dataCollectionService.getById(collectionId);
            if (dataCollection == null) {
                result.put("code", 404);
                result.put("message", "采集数据不存在");
                return result;
            }
            
            // 执行标识码校验
            boolean identifierCheckResult = performIdentifierCheck(dataCollection);
            
            // 创建入库记录
            DataStorage dataStorage = new DataStorage();
            dataStorage.setCollectionId(collectionId);
            dataStorage.setStorageTime(new Date());
            dataStorage.setIdentifierCheck(identifierCheckResult ? 1 : 2);
            dataStorage.setVersion(1);
            
            boolean storageSuccess = dataStorageService.save(dataStorage);
            
            if (storageSuccess) {
                // 更新采集数据状态
                dataCollection.setStatus(2); // 已入库
                dataCollectionService.updateById(dataCollection);
                
                result.put("code", 200);
                result.put("message", "数据入库成功");
                result.put("data", dataStorage);
            } else {
                result.put("code", 500);
                result.put("message", "数据入库失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取待入库数据列表
     */
    @OperationLog(bizModule = 1, bizType = 5, description = "查询待入库数据列表", recordParams = false)
    @GetMapping("/pendingList")
    public Map<String, Object> getPendingList(@RequestParam(defaultValue = "1") Integer page,
                                            @RequestParam(defaultValue = "10") Integer size,
                                            @RequestParam(required = false) String customsArea) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("status", 1); // 待入库状态
            if (customsArea != null && !customsArea.isEmpty()) {
                queryParams.put("customsArea", customsArea);
            }
            
            // 分页查询待入库数据
            List<DataCollection> dataList = dataCollectionService.getPageList(page, size, queryParams);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", dataList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取关区配置列表
     */
    @OperationLog(bizModule = 1, bizType = 5, description = "查询关区配置列表", recordParams = false)
    @GetMapping("/customsAreaList")
    public Map<String, Object> getCustomsAreaList() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<CustomsAreaConfig> areaList = customsAreaConfigService.list();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", areaList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取用户列表
     */
    @OperationLog(bizModule = 1, bizType = 5, description = "查询用户列表", recordParams = false)
    @GetMapping("/userList")
    public Map<String, Object> getUserList() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<SysUser> userList = sysUserService.list();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", userList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 解析CSV文件
     */
    private List<DataCollection> parseCsvFile(MultipartFile file, String customsArea, Integer userId) {
        List<DataCollection> dataList = new ArrayList<>();
        try {
            String content = new String(file.getBytes(), "UTF-8");
            String[] lines = content.split("\n");
            
            // 跳过标题行，从第二行开始解析
            for (int i = 1; i < lines.length; i++) {
                String line = lines[i].trim();
                if (!line.isEmpty()) {
                    String[] fields = line.split(",");
                    if (fields.length >= 6) {
                        DataCollection data = new DataCollection();
                        data.setDataType(2); // CSV上报
                        data.setCustomsArea(customsArea);
                        data.setDeclareNo(fields[0].trim());
                        data.setItemNo(fields[1].trim());
                        data.setCurrencyType(Integer.parseInt(fields[2].trim()));
                        data.setAmountCny(Double.parseDouble(fields[3].trim()));
                        data.setAmountUsd(Double.parseDouble(fields[4].trim()));
                        data.setGoodsQuantity(Integer.parseInt(fields[5].trim()));
                        data.setStatus(1); // 待入库
                        data.setCreateTime(new Date());
                        data.setUserId(userId);
                        
                        dataList.add(data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    /**
     * 执行标识码校验
     */
    private boolean performIdentifierCheck(DataCollection dataCollection) {
        // 简单的标识码校验逻辑
        // 实际项目中可以根据具体业务规则进行校验
        try {
            String declareNo = dataCollection.getDeclareNo();
            String itemNo = dataCollection.getItemNo();
            
            // 检查报关单号格式（示例：长度应为18位）
            if (declareNo == null || declareNo.length() != 18) {
                return false;
            }
            
            // 检查项号格式（示例：应为3位数字）
            if (itemNo == null || !itemNo.matches("\\d{3}")) {
                return false;
            }
            
            // 检查金额是否合理
            if (dataCollection.getAmountCny() == null || dataCollection.getAmountCny() <= 0) {
                return false;
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
